package com.agiantii.ablog.mapper;

import com.agiantii.ablog.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface UserMapper {
    
    @Select("SELECT * FROM user WHERE username = #{username} AND deleted = 0")
    User findByUsername(String username);
    
    @Select("SELECT * FROM user WHERE email = #{email} AND deleted = 0")
    User findByEmail(String email);
    
    @Select("SELECT * FROM user WHERE id = #{id} AND deleted = 0")
    User findById(Long id);
    
    @Insert("INSERT INTO user(username, password, email, avatar, bio) " +
            "VALUES(#{username}, #{password}, #{email}, #{avatar}, #{bio})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(User user);
    
    @Update("UPDATE user SET username = #{username}, avatar = #{avatar}, bio = #{bio}, " +
            "updated_at = CURRENT_TIMESTAMP WHERE id = #{id} AND deleted = 0")
    int update(User user);
    
    @Update("UPDATE user SET deleted = 1 WHERE id = #{id}")
    int deleteById(Long id);
    
    @Select("SELECT * FROM user WHERE deleted = 0")
    List<User> findAll();
    
    @Select("<script>" +
            "SELECT * FROM user WHERE id IN " +
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            " AND deleted = 0" +
            "</script>")
    List<User> findByIds(@Param("ids") List<Long> ids);
    
    @Select("SELECT COUNT(*) FROM post WHERE user_id = #{userId} AND deleted = 0")
    long countUserPosts(Long userId);
}
